from rest_framework.renderers import JSONRenderer


class MyJsonRenderer(JSONRenderer):
    """
        重构render方法，重新构造data参数
        data = {
            'code': 200,
            'msg': '请求成功',
            ’data‘: {}
        }
    """

    def render(self, data, accepted_media_type=None, renderer_context=None):
        # data: {'code': 1001, 'msg': '账号已存在'}
        # data: {'user_id':12}
        if isinstance(data, dict):
            code = data.pop('code') if data.get('code') else 200
            msg = data.pop('msg') if data.get('msg') else '请求成功'
        else:
            code = 200
            msg = '请求成功'
        # 将所有请求的状态码都修改为200
        renderer_context['response'].status_code = 200

        res = {
            'code': code,
            'msg': msg,
            'data': data
        }
        return super().render(res)



